/*
  学习目标：useEffect容器踩坑点

*/
import React, { useState } from "react";
import { useEffect } from "react";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Main from "./components/Main";
import "./styles/base.css";
import "./styles/index.css";

export default function App() {
  const [list, setList] = useState([]);

  // 💥书写多个 useEffect 时，注意先后书写顺序。(先书写组件挂载时，再书写组件更新时)
  // 挂载
  useEffect(() => {
    const newList = JSON.parse(localStorage.getItem("todo-list-81"));
    setList(newList);
  }, []);

  // 更新:  挂载更新二合一
  // 💥 先声明 ,后监听
  useEffect(() => {
    console.log("挂载时执行一次, 存缓存  ----->  ", list);
    localStorage.setItem("todo-list-81", JSON.stringify(list));
  }, [list]);

  const [type, setType] = useState("all");

  const handleUpdateById = (id) => {
    const newList = list.map((item) => ({
      ...item,
      isDone: item.id === id ? !item.isDone : item.isDone,
    }));

    setList(newList);
  };

  const handleDeyById = (id) => {
    const newList = list.filter((item) => item.id !== id);
    setList(newList);
  };

  const handleAdd = (task) => {
    const newItem = {
      task,
      id: Date.now(),
      isDone: false,
    };
    setList([newItem, ...list]);
  };

  const handleUpdateType = (type) => {
    setType(type);
  };

  const showList = list.filter((item) => {
    if (type === "all") return true;

    if (type === "active") return !item.isDone;

    return item.isDone;
  });

  return (
    <section className="todoapp">
      <Header handleAdd={handleAdd} />
      <Main
        list={showList}
        handleDeyById={handleDeyById}
        handleUpdateById={handleUpdateById}
      />
      <Footer type={type} handleUpdateType={handleUpdateType} />
    </section>
  );
}
